package com.thememaker.lockstyle;

import com.thememake.util.ZipUtil;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.nio.file.Paths;


public final class FileToZip {
    /**
     * 文件读取缓冲区大小
     */

    public FileToZip() {

    }

    public static void weileToZip(String poppath, String filepath, String datapath,String locstyle,long timepath){
        System.out.println(timepath);
        docopy(poppath, filepath, datapath,timepath);
        dozip(poppath, locstyle,timepath);
    }
    /**
     * 文件复制的具体方法
     */
    public static void docopy(String poppath, String filepath, String datapath,long timepath) {
        String lockpath25 = "/lockscreen2_5/" + timepath;
        String lockpath30 = "/lockscreen3_0/lockscreen/" + timepath;
        String path25 = "/lockscreen2_5/" + timepath + "/wallpaper/artwork/20180912/743218/pop";
        String data25 = "/lockscreen2_5/" + timepath + "/wallpaper/artwork/20180912/743218";
        String path30 = "/lockscreen3_0/lockscreen/" + timepath + "/wallpaper/artwork/20180912/743218/pop";
        String data30 = "/lockscreen3_0/lockscreen/" + timepath + "/wallpaper/artwork/20180912/743218";
        File file_bg = new File(poppath + path25);
        file_bg.mkdirs();
        File file_bg2 = new File(poppath + path30);
        file_bg2.mkdirs();
        try {
            FileToZip.copy(poppath + "/lockscreen", poppath + lockpath25);
            FileToZip.copy(poppath + "/lockscreen", poppath + lockpath30);
            System.out.println(">>>>>>>>"+datapath+">>>>>"+poppath);
            /*FileToZip.copy(poppath + "/data", datapath);*/
            FileToZip.copy(datapath, poppath + data25);
            FileToZip.copy(datapath, poppath + data30);
            FileToZip.copy(filepath, poppath + path25);
            FileToZip.copy(filepath, poppath + path30);
            FileToZip.formatPath(poppath+data25);
            FileToZip.formatPath(poppath+data30);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public static long testSystem(long times) {//use 188
        long currentTime = 0;
        for (int i = 0; i < times; i++) {
            currentTime = System.currentTimeMillis();
        }
        return currentTime;
    }

    public static void dozip(String poppath, String locstyle,long timepath) {
        FileToZip fileToZip = new FileToZip();
        File file_bg = new File(poppath + "\\zip\\25");
        file_bg.mkdirs();
        File file_bg3 = new File(poppath + "\\zip\\30");
        file_bg3.mkdirs();
        System.out.println(file_bg + "----" + file_bg3);
        String zip2_5 = poppath+"\\lockscreen2_5\\";
        String zip3_0 = poppath+"\\lockscreen3_0\\";
        try {
            System.err.println("开始打包>>>>>>>>>>>");
            System.out.println(Paths.get(zip2_5,String.valueOf(timepath)).toString());

            System.out.println(Paths.get(file_bg.getPath(),timepath + ".zip").toString());
            ZipUtil.zip(Paths.get(zip2_5, String.valueOf(timepath)).toFile(),Paths.get(file_bg.getPath(),String.valueOf(timepath) + ".zip").toFile());

            System.out.println("第一步完成");
            setXml25(zip2_5 + "\\lockscreen.xml",timepath);
            setXml30(zip3_0 + "\\description.xml",timepath);
            fileCopy(poppath + "\\lockscreen2_5\\lockscreen.xml", String.valueOf(file_bg) + "\\"+timepath+".xml");
            fileCopy(zip3_0 + "\\description.xml", String.valueOf(file_bg3) + "\\description.xml");
            File file_bg5 = new File(String.valueOf(file_bg3) + "\\lockscreen");
            file_bg5.mkdirs();
            File file = new File(zip3_0 + "\\lockscreen/" + timepath);

            ZipUtil.zip(file,new File(String.valueOf(file_bg3) + "\\lockscreen\\" + timepath + ".zip"));
            ZipUtil.zip(file_bg,new File(locstyle + "\\lockscreen.iuz"));
            ZipUtil.zip(file_bg3,new File(locstyle + "\\lockscreen.itz"));
            System.out.println("打包完成");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        fileToZip.DeleteFolder(zip2_5 + timepath);
        fileToZip.DeleteFolder(zip3_0 + "\\lockscreen");
        fileToZip.DeleteFolder(poppath + "\\zip");
    }

    public static void fileCopy(String src, String des) throws Exception {
        //io流固定格式
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(des));
        int i = -1;//记录获取长度
        byte[] bt = new byte[2014];//缓冲区
        while ((i = bis.read(bt)) != -1) {
            bos.write(bt, 0, i);
        }
        bis.close();
        bos.close();
        //关闭流
    }


    public boolean DeleteFolder(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 判断目录或文件是否存在
        if (!file.exists()) {  // 不存在返回 false
            return flag;
        } else {
            // 判断是否为文件
            if (file.isFile()) {  // 为文件时调用删除文件方法
                return deleteFile(sPath);
            } else {  // 为目录时调用删除目录方法
                return deleteDirectory(sPath);
            }
        }
    }

    public boolean deleteDirectory(String sPath) {
        //如果sPath不以文件分隔符结尾，自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在，或者不是一个目录，则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        boolean flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

    public boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }

    public static Document loadXml(String path) {
        File file = new File(path);
        Document document = null;
        if (file != null && file.exists() && file.isFile()) {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = null;
            FileInputStream fileInputStream = null;
            try {
                builder = factory.newDocumentBuilder();
                fileInputStream = new FileInputStream(file);
                InputSource inputSource = new InputSource(fileInputStream);
                inputSource.setEncoding("utf-8");
                document = builder.parse(inputSource);
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } finally {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } else {
            System.out.println("文件不存在");
        }
        return document;
    }

    public void saveXml(Document document, File file) throws TransformerException {
        document.getDocumentElement().normalize();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(file);
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.transform(source, result);
    }

    /**
     * x修改后缀名
     */
    public static void formatPath(String path) throws Exception {
        File file = new File(path);
        //得到文件夹下的所有文件和文件夹
        String[] list = file.list();
        if (list != null && list.length > 0) {
            for (String oldName : list) {
                File oldFile = new File(path, oldName);
                //判断出文件和文件夹
                if (!oldFile.isDirectory()) {
                    //文件则判断是不是要修改的
                    /*.文件后缀修改*/
                    if (oldName.contains(".lua")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlm";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".png")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlb";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".jpg")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vld";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".swf")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vla";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".gif")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlc";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".bmp")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vle";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".avi")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlf";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".mp4")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlg";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".flv")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlh";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".txt")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vli";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".data")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlj";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".send")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlk";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".plist")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vll";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".js")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vln";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".ccbi")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlo";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".zip")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlp";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".pkm")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlq";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    } else if (oldName.contains(".svl")) {
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".vlr";
                        File newFile = new File(path, newoldName);
                        oldFile.renameTo(newFile);
                    }
                } else {
                    //文件夹则迭代
                    String newpath = path + "/" + oldName;
                    formatPath(newpath);
                }
            }
        }
    }

    /**
     * 修改bg.jpg
     */
    public static void formatBg(String path) throws Exception {
        File file = new File(path);
        //得到文件夹下的所有文件和文件夹
        String[] list = file.list();
        if (list != null && list.length > 0) {
            for (String oldName : list) {
                File oldFile = new File(path, oldName);
                //判断出文件和文件夹
                if (!oldFile.isDirectory()) {
                    //文件则判断是不是要修改的
                    /*.文件后缀修改*/
                    if (oldName.contains(".jpg")){
                        String newoldName = oldName.substring(0, oldName.lastIndexOf(".")) + ".default";
                        File newFile = new File(path, newoldName);
                        System.out.println(newoldName+"___"+oldName);
                        oldFile.renameTo(newFile);
                    }
                } else {
                    //文件夹则迭代
                    String newpath = path + "/" + oldName;
                    formatBg(newpath);
                }
            }
        }
    }

    public static void copy(String src, String des) throws Exception {
        //初始化文件复制
        File file1 = new File(src);
        //把文件里面内容放进数组
        File[] fs = file1.listFiles();
        //初始化文件粘贴
        File file2 = new File(des);
        //判断是否有这个文件有不管没有创建
        if (!file2.exists()) {
            file2.mkdirs();
        }
        //遍历文件及文件夹
        for (File f : fs) {
            if (f.isFile()) {
                //文件
                fileCopy(f.getPath(), des + "\\" + f.getName()); //调用文件拷贝的方法
            } else if (f.isDirectory()) {
                //文件夹
                copy(f.getPath(), des + "\\" + f.getName());//继续调用复制方法      递归的地方,自己调用自己的方法,就可以复制文件夹的文件夹了
            }
        }

    }

    /**
     * 3.0修改XML
     */
    private static void setXml30(String fileName,long timepath) throws IOException, TransformerException {
        System.out.println("保存30"+timepath);
        Document document = FileToZip.loadXml(fileName);
        setXml("id",document,true,timepath);
        setXml("title",document,false,timepath);
        setXml("author",document,false,timepath);
        setXml("description",document,false,timepath);
        new FileToZip().saveXml(document, new File(fileName));
    }

    public static void setXml(String name,Document document,Boolean type,long timepath){
        NodeList nodeList = document.getDocumentElement().getElementsByTagName(name);
        if(type){
            nodeList.item(0).setTextContent(timepath + "");
        }else{
            nodeList.item(0).setTextContent("");
            nodeList.item(0).appendChild(document.createCDATASection(timepath + ""));
        }
    }
    /**
     * 2.5修改XML
     */
    private static void setXml25(String fileName,long timepath) throws IOException, TransformerException {
        System.out.println("保存25"+timepath);
        Document document = FileToZip.loadXml(fileName);
        setXml("id",document,true,timepath);
        setXml("name",document,true,timepath);
        setXml("description",document,false,timepath);
        setXml("author",document,true,timepath);
        new FileToZip().saveXml(document, new File(fileName));
    }
}
